/*
 * @Author: Wilbur
 * @Date: 2019-04-10 15:38:21
 * @Last Modified by: Wilbur
 * @Last Modified time: 2019-06-13 17:22:10
 * 合同列表
 */

<template>
    <div class="container cantract-list-container">
        <div class="content-wrapper">
            <el-row
                class="search-wrapper"
                :gutter="20"
            >
                <el-form
                    label-position="right"
                    label-width="84px"
                    ref="searchfrom"
                    size="small">


                    <el-form-item label="公司名称">
                        <el-input
                            v-model.trim="filterData.company_name"
                            placeholder="请输入公司名称"
                            type="text"
                            size="small"
                            style="width: 193px;"
                            @keyup.native.enter="getTableData()"
                        />
                    </el-form-item>

                    <el-form-item label="合同编号">
                        <el-input
                            v-model.trim="filterData.contract_no"
                            placeholder="合同编号"
                            type="text"
                            size="small"
                            style="width: 193px;"
                            @keyup.native.enter="getTableData()"
                        />
                    </el-form-item>

                    <el-form-item label="开始时间">
                        <el-date-picker
                            v-model="filterData.start_time"
                            value-format="timestamp"
                            type="datetime"
                            @change="getTableData()"
                            placeholder="选择开始时间"
                            style="width: 193px;"/>
                    </el-form-item>

                    <el-form-item label="结束时间">
                        <el-date-picker
                            type="datetime"
                            placeholder="选择结束时间"
                            value-format="timestamp"
                            v-model="filterData.end_time"
                            @change="getTableData()"
                            style="width: 193px;"/>
                    </el-form-item>
                    <el-button
                        size="small"
                        style="margin-left: 18px;"
                        @click="fnResetFrom('searchfrom')"
                    >重置筛选</el-button>
                    <el-button
                        size="small"
                        type="primary"
                        style="margin-left: 18px;"
                        @click="getTableData()"
                    >搜索</el-button>
                </el-form>
            </el-row>
            <div class="table-wrapper">
                <el-table
                    :data="tableData"
                    height="100%"
                    style="width: 100%;"
                >
                    <el-table-column
                        prop="contract_no"
                        label="合同编号"
                        width="180px"
                    />
                    <el-table-column
                        prop="company_name"
                        :formatter="emptyFormatter"
                        show-overflow-tooltip
                        label="公司名称"
                    />
                    <el-table-column
                        header-align="left"
                        label="合同类型"
                    >
                        <template slot-scope="scope">
                            <template v-if="scope.row.type == 1">媒介投放</template>
                            <template v-if="scope.row.type == 2">会员合同</template>
                            <template v-if="scope.row.type != 1 && scope.row.type != 2">--</template>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="need_invoice"
                        label="是否需要税点">
                        <template slot-scope="scope">
                            <span v-if="scope.row.need_invoice == 1">是</span>
                            <span v-if="scope.row.need_invoice == 0">否</span>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="money"
                        label="合同金额(6%税点)"
                    />

                    <el-table-column
                        prop="create_time"
                        label="合同生成时间">
                        <template slot-scope="scope">
                            {{ scope.row.create_time*1000 | dateFormatter('yyyy/MM/dd HH:mm') }}
                        </template>
                    </el-table-column>


                    <el-table-column
                        prop="status"
                        label="下载状态">
                        <template slot-scope="scope">
                            <template v-if="scope.row.status == 1">已下载</template>
                            <template v-if="scope.row.status == 2">未下载</template>
                            <template v-if="scope.row.status == -1">已取消</template>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="status"
                        label="支付状态">
                        <template slot-scope="scope">
                            <template v-if="scope.row.pay_status == 0">未支付</template>
                            <template v-if="scope.row.pay_status == 1">已支付</template>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="simple_content"
                        :formatter="emptyFormatter"
                        show-overflow-tooltip
                        label="购买内容"/>

                    <el-table-column
                        prop="money_type"
                        label="资源排期">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                :disabled="scope.row.status == -1 ? true : false"
                                @click="handleRoute('resourceSchedule', {contract_no: scope.row.contract_no})">资源排期</el-button>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="date"
                        label="操作"
                        fixed="right"
                        :width="220"
                    >
                        <template slot-scope="scope">
                            <div>
                                <el-button
                                    type="text"
                                    @click="fnExportData(scope.row.contract_no, 1)"
                                >预览合同</el-button>
                                <el-button
                                    type="text"
                                    v-if="scope.row.can_pay == 1 && scope.row.pay_status == 0"
                                    @click="fnChangePrice(scope.row.contract_no, scope.row.money_ori)"
                                >修改合同金额</el-button>

                                <el-button
                                    type="text"
                                    v-if="scope.row.refund_apply == 1"
                                    title="退款至钱包"
                                    :disabled="!authResult.auth_refused"
                                    @click="fnPriceBack(scope.row.contract_no)"
                                >退款</el-button>
                                <el-button
                                    type="text"
                                    v-if="scope.row.refund_apply == 1"
                                    title="驳回退款申请"
                                    :disabled="!authResult.auth_refused"
                                    @click="fnRejectPrice(scope.row.contract_no)"
                                >拒绝退款</el-button>
                                <!-- <el-button
                                    type="text"
                                    @click="fnExportData(scope.row.contract_no, 0)"
                                >下载合同</el-button>
                                <el-button
                                    type="text"
                                    @click="fnExportData(scope.row.contract_no, 0)"
                                >取消合同</el-button> -->
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination-wrapper clearfix">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="page.now_page"
                    :total="page.total_count"
                    :page-size="page.page_size"
                    @current-change="getTableData"
                />
            </div>
        </div>
        <!-- 修改合同金额 -->
        <el-dialog
            title="修改金额"
            width="470px"
            :visible.sync="dialogFormUpdatePrice">
            <el-form
                :model="form"
                :rules="rules"
                ref="ruleFormPrice">
                <el-form-item
                    label="原金额："
                    label-width="100px">
                    <el-input
                        v-model="priceOri"
                        readonly
                        class="ori-price"
                        type="number"/>
                </el-form-item>
                <el-form-item
                    label="修改金额："
                    prop="money"
                    label-width="100px">
                    <el-input
                        v-model="form.money"
                        placeholder="请输入金额"
                        type="number"/>
                </el-form-item>
            </el-form>
            <div
                slot="footer"
                class="dialog-footer">
                <el-button @click="fnResetFormPrice('ruleFormPrice')">取 消</el-button>
                <el-button
                    type="primary"
                    @click="fnSubmitChangPrice('ruleFormPrice')"
                >确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    components: {},
    data() {
        var checkMoney = (rule, value, callback) => {
            if (!value || value <= 0) {
                return callback(new Error('请输入正确的金额'));
            }else{
                callback();
            }
        };

        return {
            authResult: {},
            tableData: [],
            filterData: {
                start_time: '',
                end_time: '',
                company_name: '',
                contract_no: ''
            },
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            currTime: 0,
            dialogFormUpdatePrice: false,
            form: {
                resource_change: '',
                money: '',
            },
            rules: {
                money: [
                    { required: true, message: '请输入修改金额', trigger: 'blur' },
                    { validator: checkMoney, trigger: 'blur' }
                ]
            },
            formLabelWidth: '120px',
            priceOri: 0,
            contract_no: '',
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', [
            {
                title: "广告系统",
            },
            {
                title: '企业合同'
            }
        ]);
        this.filterData.start_time = this.$route.query.start_time ? this.$route.query.start_time : '';
        this.filterData.end_time = this.$route.query.end_time ? this.$route.query.end_time : '';
        this.filterData.company_name = this.$route.query.company_name ? this.$route.query.company_name : '';
        this.filterData.contract_no = this.$route.query.contract_no ? this.$route.query.contract_no : '';

        this.getTableData(this.$route.query.page);
    },
    filters: {
        emptyFilter(val){
            if (!val) {
                return '--';
            }
            return val;
        }
    },
    methods: {
        fnSetOrderStatus(order_no, type) {
            let data = {};

            data.type = type;
            data.order_no = order_no;
            //完成
            if(type == 1) {
                this.$prompt('请输入完成后备注', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(({ value }) => {
                    data.complete_remark = value;
                    this.fnSetOrder(data);
                }).catch(() => {
                });
            }else if(type == 3) {
                //拒绝
                this.$prompt('请输入拒绝原因', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /\S/,
                    inputErrorMessage: '请输入拒绝原因'
                }).then(({ value }) => {
                    data.refuse_reason = value;
                    this.fnSetOrder(data);
                }).catch(() => {
                });
            }else{
                //自动打款
                this.fnSetOrder(data);
            }
        },
        fnSetOrder(data) {
            this.$post('/wei4/finance%5Cfinance_system_order%5Cset_status', data, resp => {

                if (resp.code == 1) {
                    this.getTableData();
                    this.$message({
                        type: 'success',
                        message: '操作成功',
                        center: true
                    });
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },
        fnExportData(contract_no, preview) {
            let ticket = localStorage.getItem('sessionTicket');
            let base = this.$baseUrl;

            window.open(`${base}/wei4/hire_contract%5Cdownload?contract_no=${contract_no}&preview=${preview}&__ticket=${ticket}`);
        },
        fnChangePrice(contract_no, price) {
            this.contract_no = contract_no;
            this.priceOri = price;
            this.dialogFormUpdatePrice = true;
        },
        fnRejectPrice(contract_no) {
            this.$prompt('请输入驳回退款的理由', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /\S/,
                inputErrorMessage: '请输入理由'
            }).then(({ value }) => {
                this.$confirm('此操作将驳回用户申请的退款, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$post('/wei4/hire_contract%5Crefund', {
                        contract_no: contract_no,
                        type: 2,
                        refuse_reason: value
                    }, resp => {
                        if (resp.code == 1) {
                            this.getTableData();
                            this.$message({
                                type: 'success',
                                message: '操作成功',
                                center: true
                            });
                        } else {
                            this.$message({
                                type: 'warning',
                                message: resp.msg,
                                center: true
                            });
                        }
                    });
                }).catch(() => {
                });
            }).catch(() => {
            });
        },
        fnPriceBack(contract_no) {
            this.$confirm('此操作将合同金额退至用户钱包, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/wei4/hire_contract%5Crefund', {
                    contract_no: contract_no,
                    type: 1
                }, resp => {
                    if (resp.code == 1) {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '操作成功',
                            center: true
                        });
                    } else {
                        this.$message({
                            type: 'warning',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            }).catch(() => {
            });
        },
        fnSubmitChangPrice(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$post('/wei4/hire_contract%5Cchange_money', {
                        contract_no: this.contract_no,
                        money: this.form.money
                    }, resp => {

                        if (resp.code == 1) {
                            this.fnResetFormPrice(formName);
                            this.getTableData();
                            this.$message({
                                type: 'success',
                                message: '操作成功',
                                center: true
                            });
                        } else {
                            this.$message({
                                type: 'warning',
                                message: resp.msg,
                                center: true
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        fnResetFormPrice(formName) {
            this.$refs[formName].resetFields();
            this.dialogFormUpdatePrice = false;
        },
        fnResetFrom(formName) {
            this.filterData = {
                start_time: '',
                end_time: '',
                company_name: ''
            };
            this.getTableData();
        },
        /**
       * 获取表格数据
       */
        getTableData(page) {
            let time = new Date().getTime();

            this.currTime = time;

            this.$router.replace({
                query: {
                    ...this.filterData,
                    page: page || this.page.now_page
                }
            });
            this.$post('/wei4/hire_contract%5Cget_list', {
                ...this.filterData,
                page_id: page || this.page.now_page,
                page_size: 20,
            }, resp => {
                if(this.currTime != time){
                    return ;
                }
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                    if (this.page.now_page > resp.data.page.total_page && this.page.now_page !== 1) {
                        this.getTableData(resp.data.page.total_page);
                    }
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },

        /**
       * 跳转页面
       */
        handleRoute(name, query) {
            let obj = {
                name
            };

            if (query) {
                obj.query = query;
            }

            this.$router.push(obj);
        },

        /**
       * 列表渲染辅助函数：列表项为空处理
       */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        }
    }
};
</script>

<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    width: 100%;
  }
  .operation-wrapper {
    display: flex;
    flex-direction: row-reverse;
    padding: 12px 23px;
    background-color: #fff;

    .el-button {
      margin-left: 10px;
    }
  }
  .content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 15px;
    overflow: hidden;
  }
  .search-wrapper {
    padding: 15px;
    background-color: #fff;
  }
  .filter-item {
    .el-form-item {
      white-space: nowrap;
    }
    .el-input {
      width: auto;
      vertical-align: middle;
    }
    .el-button {
      margin-left: 15px;
      vertical-align: middle;
    }
  }
  .table-wrapper {
    flex: 1;
    background-color: #fff;

    .el-button {
      padding: 0;
    }
    .icon-bianji {
      font-size: 14px;
      color: #b9b9b9;
      cursor: pointer;
    }
    .btn-delete {
      color: #fd4d32;
      &.is-disabled {
        color: #c0c4cc;
        cursor: not-allowed;
      }
    }
    .submit-config-item {
      display: inline-block;
      position: relative;
      padding-right: 10px;
      font-size: 14px;

      & + .submit-config-item {
        padding-left: 10px;
        &::before {
          content: "";
          position: absolute;
          top: 50%;
          left: 0;
          width: 1px;
          height: 14px;
          transform: translate(0, -50%);
          background-color: #d8d8d8;
        }
      }

      .num {
        vertical-align: middle;
      }
      .iconfont {
        font-size: 16px;
        color: #b9b9b9;
        vertical-align: middle;
      }

      .icon-tupian {
        font-size: 20px;
      }
    }
  }
  .pagination-wrapper {
    padding-top: 10px;
    .el-pagination {
      float: right;
      padding: 0;
      background-color: transparent;
    }
  }
  .dialog-link {
    & + .dialog-link {
      margin-top: 20px;
    }
    .link-label {
      font-weight: 500;
      margin-right: 20px;
    }
    .link-value {
    }
  }
</style>
<style lang="less">
.cantract-list-container{
    .search-wrapper{
        .el-form-item{
            display: inline-block;
        }
    }
    .ori-price{
        input{
            border: none;
        }
    }
}
</style>
